<?php

//生成不重复的字符串
function getRandCode($len){
    $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    $string=time();
    for(;$len>=1;$len--)
    {
        $position=rand()%strlen($chars);
        $position2=rand()%strlen($string);
        $string=substr_replace($string,substr($chars,$position,1),$position2,0);
    }

    return $string;
}


//金钱格式化
function money_number_format($money){
    return number_format($money,0,'.',',');
}

/*
**获取今日，昨日，上周，上一个月，上三个月的开始时间戳与结束时间戳
**@param string $value  1今天,2昨日,3上周,4上一个月,5上三个月
*/
function getTimestampArr($value){
	$today = mktime(0,0,0,date('m'),date('d'),date('Y'));
    if($value == 1){
    	$array[0] = $today;
    	$array[1] = time();
    }else if($value == 2){
    	$array[0] = $today-86400;
    	$array[1] = $today-1;
    }else if($value == 3){
    	$array[0] = $today-604800;
    	$array[1] = $today-1;
    }else if($value == 4){
    	$array[0] = $today-2592000;
    	$array[1] = $today-1;
    }else if($value ==5){
        $array[0] = $today-7776000;
        $array[1] = $today-1;
    }

    return $array;
}


//格式化用户使用时长
function formatDuration($duration){
    if($duration < 60 ){
        return $duration.'秒';
    }

    if($duration>=60 ){
        $duration = floor($duration/60);
        return $duration.'分钟';
    }
}


//获取智能柜的编号
function getClubName($box_id){
	$Box     = M('Box');
	return $Box->where('id = '.$box_id)->getField('number');
}

//获取智能柜下的两个控制板编号
function getControlBoardNumber($box_id){
	return M('control_board')->where('box_id = '.$box_id)->order('`order` asc')->getField('number',true);
}

//获取用户的手机号
function getUserMobile($user_id){
    return M('User')->where('id = '.$user_id)->getField('mobile');
}

//获取杆锁对应的编号
function getLockCueNumber($lock_id){
    return M('lock')->where('id = '.$lock_id)->getField('cue_number');
}

function getAccessToken(){
	$Wxapp_config = M('wxapp_config');
                //判断是否过了缓存期
    $wechat = $Wxapp_config->find();
    $expire_time = $wechat['expires'];
    if(!empty($wechat['access_token']) && $expire_time > time()){
        return $wechat['access_token'];
    }
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$wechat['appid']}&secret={$wechat['secret']}";
 
    $result  = httpRequest($url,'GET');
    $return  = json_decode($result,true);
    $expires = time() + 7000; // 提前200秒过期
    $Wxapp_config->where('id',$wechat['id'])->save(array('access_token'=>$return['access_token'],'expires'=>$expires));
    return $return['access_token'];
}
